LeetCode Js-409. Longest Palindrome
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
給予一個有大寫或小寫的字串 s,回傳可組成最長的字串。
(ex.
左右對稱:noon
中心對稱:radar, level)
Example 1:
Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
Solution:
- 剩餘 0: 長度加上此字母的個數
- 不剩餘 0: 長度加上此字母的個數 - 1 (此數中心點,故須 - 1)
且符合中心對稱條件。
- condition = true: 長度 + 1
- condition = false: 長度維持不變
Code:
var longestPalindrome = function(s) {
const counts = {}
let length = 0, condition = false
for (let i = 0; i < s.length; i++) {
counts[s[i]] = (counts[s[i]] || 0) + 1
}
for (let letter in counts) {
if (counts[letter] % 2 === 0) {
length += counts[letter]
} else {
condition = true
length += counts[letter] - 1
}
}
if (condition) {length += 1}
return length
}
FlowChart:
Example 1
Input: s = "abccccdd"
length = 0, condition = false
counts = {a: 1}
counts = {a: 1, b: 1}
counts = {a: 1, b: 1, c: 1}
counts = {a: 1, b: 1, c: 2}
counts = {a: 1, b: 1, c: 3}
counts = {a: 1, b: 1, c: 4}
counts = {a: 1, b: 1, c: 2, d: 1}
counts = {a: 1, b: 1, c: 4, d: 2}
step.1
counts[letter] % 2 = 1 //{ a: 1}, 1 % 2 = 1
condition = true
length += counts[letter] - 1 //0 + 1 - 1 = 0
step.2
counts[letter] % 2 = 1 //{ b: 1}, 1 % 2 = 1
condition = true
length += counts[letter] - 1 //0 + 1 - 1 = 0
step.3
counts[letter] % 2 = 0 //{ c: 4}, 4 % 2 = 0
condition = true
length += counts[letter] //0 + 4 = 4
step.4
counts[letter] % 2 = 0 //{ d: 2}, 2 % 2 = 0
condition = true
length += counts[letter] //4 + 2 = 6
step.5
condition = true => length += 1 = 6 + 1 = 7
(ex.符合中心對稱,故對稱的長度再加上中心點。
return length //7